using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.UI;

public class ScreenFader : MonoBehaviour
{
    // 单例模式
    public static ScreenFader Instance { get; private set; }

    public CanvasGroup faderCanvasGroup; // 控制淡入淡出的CanvasGroup组件

    public float fadeDuration = 1f; // 淡入淡出持续时间

    private void Awake()
    {
        // 实现单例模式
        if (Instance == null)
        {
            Instance = this;
        }
        else if (Instance != this)
        {
            Destroy(gameObject);
        }
        DontDestroyOnLoad(gameObject);  // 切换场景时保持该对象不被销毁
    }

    // 淡入场景
    public IEnumerator FadeSceneIn()
    {
        yield return StartCoroutine(Fade(0f, faderCanvasGroup));
        // 将淡入遮罩的CanvasGroup对象禁用
        faderCanvasGroup.gameObject.SetActive(false);
    }

    // 淡出场景
    public IEnumerator FadeSceneOut()
    {
        // 启用淡出遮罩的CanvasGroup对象
        faderCanvasGroup.gameObject.SetActive(true);
        yield return StartCoroutine(Fade(1f, faderCanvasGroup));
    }

    // 淡入淡出实现
    public IEnumerator Fade(float finalAlpha, CanvasGroup canvasGroup)
    {
        // 使用DOTween实现淡入淡出效果
        yield return canvasGroup.DOFade(finalAlpha, fadeDuration).WaitForCompletion();
    }
}
